package org.atf.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.atf.command.AtfLocal;
import org.atf.command.AtfRemote;
import org.atf.model.dao.AuditDAO;
import org.atf.model.dao.LdapConfigDAO;
import org.atf.model.dao.PreferenceDAO;
import org.atf.model.dao.ProfileDAO;
import org.atf.model.dao.UserDAO;
import org.atf.model.entity.Audit;
import org.atf.model.entity.LdapConfig;
import org.atf.model.entity.Preference;
import org.atf.model.entity.Profile;
import org.atf.model.entity.User;
import org.atf.services.TaskStatus;
import org.atf.utils.ATFUtils;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;



public class ProfileController {
	private ProfileDAO profileDAO = new ProfileDAO();
	private PreferenceDAO preferenceDAO= new PreferenceDAO();
	private AuditDAO auditDAO= new AuditDAO();
	private UserDAO userDAO= new UserDAO();
	private LdapConfigDAO ldapConfigDAO= new LdapConfigDAO();
	private  static Logger  logger = Logger.getLogger(ProfileController.class);
	public List<Profile> getProfilesList(){	
		return profileDAO.getProfiles();
	}
	
	public String addProfile(Profile profile){
		profileDAO.insertProfile(profile);
		String result="OK";
		return result;
	}
	
	public String updateProfile(Profile profile){
		profileDAO.updateWebProfile(profile);
		String result="OK";
		return result;
	}
	public String deleteProfile(Integer id){
		profileDAO.deleteProfile(id);
		return "OK";
	}
	
	public Profile getNewProfile(){
		Profile profile= new Profile();
		return profile;
	}
	
	public Profile getProfileId(Integer profileId){
		return profileDAO.getProfile(profileId);
	}
	
	public List<Preference> getProfilePreferencesList(Integer profileId){	
		return profileDAO.getPreference(profileId);
	}
	
	public String deleteProfilePreference(Integer profileId, Integer prefId){
		profileDAO.deletePreference(profileId, prefId);
		return "OK";
	}
	public String addPreference(Integer profileId,Preference preference){
		profileDAO.insertPreference(profileId,preference);
		return "OK";
	}
	
	public List<Audit> getAllAudit(Integer maxResult){
		return auditDAO.getAllAudit(maxResult);
	}
	public List<User> getUsersData(){
		return userDAO.getAllUser();
	}
	public String addNewUser(User user){
		userDAO.insertUser(user);
		return "OK";
	}
	
	public String updateUser(User user){
		userDAO.updateUser(user);
		return "OK";
	}
	public String deleteUsersData(Integer userid){
		userDAO.deleteUser(userid);
		return "OK";
	}
	public List<Audit> getAllAuditFiltered(Integer maxResult, HashMap<String, String> filterObj){
		HashMap<String, String> temp=new HashMap<String,String>();
		System.out.println(filterObj);
		Iterator iterator = filterObj.keySet().iterator();
		while(iterator.hasNext()){
			String key= (String) iterator.next();
			String value=filterObj.get(key);
			if(value != null && !value.equalsIgnoreCase("")){
				temp.put(key, value);
			}
		}
		return auditDAO.getAllAuditFiltered(maxResult, temp);
	}
	public List<Profile> getProfilesByType(String profileType){
		ProfileDAO profileDAO= new ProfileDAO();
		return profileDAO.getProfilesByType(profileType);
	}
	public List<Profile> getProfileByTypeRegion(String profileType, String region){
		ProfileDAO profileDAO= new ProfileDAO();
		return profileDAO.getProfileByTypeRegion(profileType,region);
	}
	public List<String> getProfileUniqueRegions(){
		ProfileDAO profileDAO= new ProfileDAO();
		return profileDAO.getProfileUniqueRegions();
	}
	public  LdapConfig getLdapConfig(){
		List<LdapConfig> list= ldapConfigDAO.getAllLdapConfig();
		if(list.size() > 0){
			return list.get(0);
			
		}
		return null;
	}
	public String addNewLdapConfig(LdapConfig ldapConfig){
		ldapConfigDAO.insertLdapConfig(ldapConfig);
		return "OK";
	}
	
	public String updateLdapConfig(LdapConfig ldapConfig){
		ldapConfigDAO.updateLdapConfig(ldapConfig);
		return "OK";
	}
	
	public String removeWasServerConfigFileProfile(Integer profileId, String appName){
		String result="ERROR:UNKNOWN";
		Preference sshEnabledPref=preferenceDAO.getPreferenceByName(profileId, 0, "SSH_ENABLED", "PROFILE");
		boolean sshEnabled= false;
		if(sshEnabledPref != null){
			sshEnabled =Boolean.parseBoolean(sshEnabledPref.getpValue());
		}
		logger.debug("profileId: "+profileId+ " appName: "+appName);
		logger.debug("sshEnabled: "+sshEnabled);
		String responseFilesPath="";
		String scriptPath="";
		Preference scriptPathPrf= preferenceDAO.getPreferenceByName(profileId, 0, "SCRIPT_PATH", "PROFILE");
		if(scriptPathPrf != null){
			scriptPath=scriptPathPrf.getpValue();
		}
		if( !scriptPath.equalsIgnoreCase("")){
			responseFilesPath=scriptPath+"/responsefiles/config";
		}else{
			responseFilesPath="/apps/scripts/v70/responsefiles/config";
		}
		logger.debug("responseFilesPath: "+responseFilesPath);
		if(sshEnabled){
			AtfRemote atfRemote= ATFUtils.getAtfRemote(profileId);
			try {
				atfRemote.deleteIfDirExists(responseFilesPath+"/"+appName);
				if(!atfRemote.checkIfDirExists(responseFilesPath+"/"+appName)){
					result= "SUCCESS: Server Folder Deleted";
				}else{
					result= "ERROR: Unabled to  Deleted the Folder";
				}
			}  catch (JSchException e) {
				// TODO Auto-generated catch block
				result="ERROR:"+e.getMessage();
			}
		}else{
			AtfLocal atfLocal= new AtfLocal();
			atfLocal.deleteIfDirExists(responseFilesPath+"/"+appName);
			if(!atfLocal.checkIfDirExists(responseFilesPath+"/"+appName)){
				result= "SUCCESS: Server Folder Deleted locally";
			}else{
				result= "ERROR: Unabled to  Deleted the Folder";
			}
		}
		
		return result;
		
	}
	public String addWasServerConfigToProfile(Integer profileId, String appName){
		String result="ERROR:UNKNOWN";
		Preference sshEnabledPref=preferenceDAO.getPreferenceByName(profileId, 0, "SSH_ENABLED", "PROFILE");
		boolean sshEnabled= false;
		if(sshEnabledPref != null){
			sshEnabled =Boolean.parseBoolean(sshEnabledPref.getpValue());
		}
		String responseFilesPath="";
		String scriptPath="";
		Preference scriptPathPrf= preferenceDAO.getPreferenceByName(profileId, 0, "SCRIPT_PATH", "PROFILE");
		if(scriptPathPrf != null){
			scriptPath=scriptPathPrf.getpValue();
		}
		if( !scriptPath.equalsIgnoreCase("")){
			responseFilesPath=scriptPath+"/responsefiles/config";
		}else{
			responseFilesPath="/apps/scripts/v70/responsefiles/config";
		}
		
		if(sshEnabled){
			AtfRemote atfRemote= ATFUtils.getAtfRemote(profileId);
			try {
				atfRemote.createDirIfNotExists(responseFilesPath+"/"+appName);
				if(atfRemote.checkIfDirExists(responseFilesPath+"/"+appName)){
					result= "SUCCESS: Server Folder created";
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				result="ERROR:"+e.getMessage();
			} catch (JSchException e) {
				// TODO Auto-generated catch block
				result="ERROR:"+e.getMessage();
			}
			
		}else{
			AtfLocal atfLocal= new AtfLocal();
			atfLocal.createDirIfNotExists(responseFilesPath+"/"+appName);
			if(atfLocal.checkIfDirExists(responseFilesPath+"/"+appName)){
				result= "SUCCESS: Server Folder created local";
			}else{
				result= "ERROR: Folder does't exits for app: "+appName;
			}
			
		}
		return result;
	}
	public List<HashMap<String,String>> getWasConfigurationServerList(Integer profileId){
		//Profile profile= profileDAO.getProfile(profileId);
		List<HashMap<String,String>> result= new ArrayList<HashMap<String,String>>();
		
		Preference sshEnabledPref=preferenceDAO.getPreferenceByName(profileId, 0, "SSH_ENABLED", "PROFILE");
		boolean sshEnabled= false;
		if(sshEnabledPref != null){
			sshEnabled =Boolean.parseBoolean(sshEnabledPref.getpValue());
		}
		String responseFilesPath="";
		String scriptPath="";
		Preference scriptPathPrf= preferenceDAO.getPreferenceByName(profileId, 0, "SCRIPT_PATH", "PROFILE");
		if(scriptPathPrf != null){
			scriptPath=scriptPathPrf.getpValue();
		}
		if( !scriptPath.equalsIgnoreCase("")){
			responseFilesPath=scriptPath+"/responsefiles/config";
		}else{
			responseFilesPath="/apps/scripts/v70/responsefiles/config";
		}
		if(sshEnabled){
			//remote connection to get list
			AtfRemote atfRemote= ATFUtils.getAtfRemote(profileId);
			try {
				List<String> files=atfRemote.getDirectoryList(responseFilesPath);
				for(String name: files){
					HashMap<String,String> temp= new HashMap<String,String>();
					temp.put("serverName", name);
					result.add(temp);
				}
			} catch (JSchException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SftpException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			//local connection to get List
			AtfLocal atfLocal= new AtfLocal();
			List<String> files=atfLocal.getDirectoryList(responseFilesPath);
			System.out.println("Files:"+files);
			for(String name: files){
				HashMap<String,String> temp= new HashMap<String,String>();
				temp.put("serverName", name);
				result.add(temp);
			}
		}
		
		
		return result;
		
	}
	public String getWasConfig(Integer profileId, String serverName){
		return ATFUtils.getWasConfig(profileId, serverName);
	}
	
	public String getWasConfigFilePath(Integer profileId, String serverName){
		String filePath=ATFUtils.getWasConfigFilePath(profileId, serverName);
		File f = new File(filePath);
		return f.getName();
	}
	public String uploadWasConfigFile(Integer profileId, String serverName, String configData){
		return ATFUtils.uploadWasConfigFile(profileId, serverName, configData);
		
	}
	
	
	public String sendAdminEmail(String subject, String message){
		logger.debug("Sending Admin Email:");
		logger.trace("Subject: "+subject);
		logger.trace("message: "+message);
		if(ATFUtils.sendTextEmail("", "", subject, message)){
			return "OK: Email Send";
		}else{
			return "WARN: Could't Send Email. Error Occured!";
		}
		
		
	}
	public String testSshConnection(String hostname,String username, String password, String port){
		String sshKnownHostFile="";
		String result="";
		Preference sshKnownHostFilePref= preferenceDAO.getPreferenceByNameScope("SSH_KNOWN_HOST_FILE", "GLOBAL");
		if(sshKnownHostFilePref != null){
			sshKnownHostFile=sshKnownHostFilePref.getpValue();
		}
		AtfRemote atfRemote = new AtfRemote(hostname,username,password, Integer.parseInt(port),sshKnownHostFile);
		try {
			if(atfRemote.testSSHConnection()){
				result= "SUCCESS: Test Successfull"; 
			}else{
				result= "ERROR: Error Occcured with connecting";
			}
			
		} catch (JSchException e) {
			// TODO Auto-generated catch block
			result= "ERROR: "+e.getMessage()+" "+e.getLocalizedMessage();
		}
		return result;
	}
}
